/*
 *	Source: http://www.yolinux.com/TUTORIALS/XML-Xerces-C.html
 */

#include <string>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <list>


#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

#include "XMLParser.h"


using namespace xercesc;
using namespace std;




void XMLParser::readTerrainConfigFile(const char * configFile, std::vector<Terrain*>& vecResult)
{
	try
	{
		if (checkFile(configFile) == -1)
		{
			throw(std::runtime_error( "XML document not available" ));
		}
		m_ConfigFileParser->parse( configFile );
		DOMDocument* xmlDoc = m_ConfigFileParser->getDocument();
		DOMElement* elementRoot = xmlDoc->getDocumentElement();
		if( !elementRoot )
		{
			throw(std::runtime_error( "empty XML document" ));
		}
		if (!XMLString::equals(elementRoot->getTagName(), m_TAG_root))
		{
			throw(std::runtime_error( "Bad root tag for this config file." ));
		}
		DOMNodeList* childrens = elementRoot->getElementsByTagName(m_TAG_ApplicationSettings);
		const  XMLSize_t nodeCount = childrens->getLength();
		for( XMLSize_t i = 0; i < nodeCount; ++i )
		{
			DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >(childrens->item(i));
			if (m_ATTR_Options.size() == XMLPARSER_NUMOPTIONS_TERRAINCONFIG)
			{
				Terrain* newTerrain = new Terrain;
				const XMLCh* xmlch_OptionA = currentElement->getAttribute(m_ATTR_Options[0]);
		
				newTerrain->setName(XMLString::transcode(xmlch_OptionA));
				DOMNodeList* childrens2 = currentElement->getElementsByTagName(m_TAG_ApplicationSettings2);
				const  XMLSize_t nodeCount2 = childrens2->getLength();
				for( XMLSize_t j = 0; j < nodeCount2; ++j )
				{
					DOMElement* currentElement2 = dynamic_cast< xercesc::DOMElement* >(childrens2->item(j));
						
					const XMLCh* xmlch_OptionB = currentElement2->getAttribute(m_ATTR_Options[1]);
					const XMLCh* xmlch_OptionC = currentElement2->getAttribute(m_ATTR_Options[2]);
					const XMLCh* xmlch_OptionD = currentElement2->getAttribute(m_ATTR_Options[3]);
					newTerrain->addRandomEncounter(atoi(XMLString::transcode(xmlch_OptionB)),
												   atoi(XMLString::transcode(xmlch_OptionC)),
												   XMLString::transcode(xmlch_OptionD));
				}
				vecResult.push_back(newTerrain);
			}
		}
	}
	catch( xercesc::XMLException& e )
	{
		char* message = xercesc::XMLString::transcode( e.getMessage() );
		ostringstream errBuf;
		errBuf << "Error parsing file: " << message << flush;
		XMLString::release( &message );
	}
}